﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Hosting;
using Ue.Extensions;

namespace Ue.Utility
{
    public class VirtualPathHelper
    {
        /// <summary>
        /// 判断虚拟路径是否为无效的
        /// 注意：判断不是无效的，但并不代表虚拟路径就是真正有效的。
        /// </summary>
        /// <param name="virtualPath"></param>
        /// <returns>无效：True</returns>
        public static bool IsMalformedVirtualPath(string virtualPath)
        {
            if (string.IsNullOrEmpty(virtualPath))
                return true;

            if (virtualPath.IndexOf("..") >= 0)
            {
                virtualPath = PathUtility.PhysicsPathSeparatorCharConvertToVirtualPathSeparatorChar(virtualPath);

                string rootPrefix = virtualPath.StartsWith("~/") ? "~/" : virtualPath.StartsWith("/") ? "/" : "";
                if (!string.IsNullOrEmpty(rootPrefix))
                {
                    string[] terms = virtualPath.Substring(rootPrefix.Length).Split('/');
                    int depth = 0;
                    foreach (var term in terms)
                    {
                        if (term == "..")
                        {
                            if (depth == 0)
                            {
                                return true;
                            }
                            depth--;
                        }
                        else
                        {
                            depth++;
                        }
                    }
                }
            }

            return false;
        }

        public static string AddUrlQuery(string pathAndQuery, string queryKey, string queryValue)
        {
            pathAndQuery= RemoveUrlQuery(pathAndQuery, queryKey);

            var split = pathAndQuery.IndexOf('?') >= 0
                ? "&"
                : "?";

            return string.Format("{0}{1}{2}={3}", pathAndQuery, split, queryKey,HttpUtility.UrlEncode(queryValue));
        }

        /// <summary>
        /// 移除url中能参数部分，即：?号之后的部分
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string RemoveUrlQuery(string url)
        {
            return RemoveUrlQuery(url, "*");
        }
        /// <summary>
        /// 根据queryKey移除Url中的参数
        /// </summary>
        /// <param name="pathAndQuery"></param>
        /// <param name="queryKey"></param>
        /// <returns></returns>
        public static string RemoveUrlQuery(string pathAndQuery, string queryKey)
        {
            if (queryKey == "*")
            {
                pathAndQuery = pathAndQuery.Split('?')[0];
            }
            else
            {
                Regex regex = new Regex("(^|[?&])" + queryKey + "=([^&]*)(&|$)", RegexOptions.IgnoreCase);

                pathAndQuery = regex.Replace(pathAndQuery, string.Empty);
            }

            return pathAndQuery.Trim().TrimEnd('?');
        }

        /// <summary>
        /// 从网址中取得Url参数
        /// </summary>
        /// <returns></returns>
        public static T GetQueryValue<T>(string url, string queryKey)
            where T : IConvertible
        {
            string queryString = string.Empty;
            Regex regex = new Regex("(^|[?&])" + queryKey + "=([^&]*)(&|$)");

            if (regex.IsMatch(url))
            {
                queryString = HttpUtility.UrlDecode(regex.Match(url).Groups[2].Value);
            }

            return queryString.As<T>();
        }
    }
}
